package com.carreirati.evaluation.domain;

import java.util.List;

import org.springframework.roo.addon.dbre.RooDbManaged;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.transaction.annotation.Transactional;

@RooJavaBean
@RooJpaActiveRecord(versionField = "", table = "appraisal", schema = "dbo")
@RooDbManaged(automaticallyDelete = true)
@RooJson
public class Appraisal {

    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
        String sqlString = "INSERT INTO appraisal_relationship (appraisal_id, question_id, is_optional)";
        sqlString += "SELECT v.*, 'Y' FROM vw_get_evaluation_default_questions v WHERE appraisal_id = '" + this.getId() + "'";
        this.entityManager().createNativeQuery(sqlString).executeUpdate();
    }

    @Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            String sqlString = "DELETE FROM appraisal_relationship WHERE appraisal_id = '" + this.getId() + "'";
            this.entityManager().createNativeQuery(sqlString).executeUpdate();
            sqlString = "DELETE FROM appraisal_results WHERE appraisal_id = '" + this.getId() + "'";
            this.entityManager().createNativeQuery(sqlString).executeUpdate();
            sqlString = "DELETE FROM appraisal WHERE id = '" + this.getId() + "'";
            this.entityManager().createNativeQuery(sqlString).executeUpdate();
        } else {
            Appraisal attached = Appraisal.findAppraisal(this.getId());
            this.entityManager.remove(attached);
        }
    }
    
    
    public static List<Appraisal> findAllAppraisalsByUserId(String userId, boolean showAsEvaluator) {
    	String aux = "";
    	if (showAsEvaluator == true)
    		aux = " OR o.appraiser.id =	'" + userId + "'";
        return entityManager().createQuery("SELECT o FROM Appraisal o WHERE (o.evaluated.id= '"+ userId +"' " + aux + ") ORDER BY o.dateFrom, o.dateTo, o.projectId.name, o.appraiser.firstName, o.evaluated.firstName", Appraisal.class).getResultList();
    }
}
